﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DDNY.WebPortals.Common;
using Google.YouTube;
using Google.GData.Client;
using System.Xml;
using KeywordsBasedMVCPortal.Models;
using Google.GData.YouTube;
using Google.GData.Extensions;
using VideoPortal.Models;

namespace VideoPortal.Controllers
{
    public class HomeController : ApplicationController
    {
        //
        // GET: /Home/


        [OutputCache(Duration = 3600, VaryByParam = "id;page")]
        public ActionResult Index(string id, string page)
        {
            if (string.IsNullOrEmpty(id))
            {
                id = "most_popular";
            }
            if (string.IsNullOrEmpty(page))
            {
                return new PermanentRedirectResult("~/Home/Index/" + id + "/0");
            }
            int pageNumber = 0;
            int.TryParse(page, out pageNumber);
            Feed<Video> feed = YoutubeHelper.GetFeedById(id, pageNumber);
            List<YoutubeFeedType> types = YoutubeHelper.GetMainYoutubeFeedTypes();
            YoutubeFeedType currentType = types.Where(a => a.FeedId == id).FirstOrDefault();
            ViewBag.Title = currentType.DisplayName;




            if (!currentType.DisplayName.Contains("Videos"))
            {
                ViewBag.Title += " Videos On The Web";
            }

            if (pageNumber > 0)
            {
                ViewBag.Title += " - Page " + pageNumber.ToString();
            }
            return View("Default", feed);
        }

        [OutputCache(Duration = 3600, VaryByParam = "id")]
        public ActionResult Show(string id)
        {
            if (string.IsNullOrEmpty(id))
            {
                return new PermanentRedirectResult("~/Home/Index/");
            }
            Video video = null;
            try
            {
                video = YoutubeHelper.GetById(id);
            }
            catch (GDataRequestException ex)
            {
                if (ex.ResponseString.Contains("Private") 
                    || ex.ResponseString.Contains("not found")
                    || ex.ResponseString.Contains("nvalid"))
                {
                    return new PermanentRedirectResult("~/");
                }
            }

            ViewBag.Title = video.Title;
            if (video.CommmentCount > 0)
            {
                Feed<Comment> comments = YoutubeHelper.GetComments(id, 0);
                ViewBag.Comments = comments;
            }
            ViewBag.RelatedVideos = YoutubeHelper.GetRelatedVideos(id);
            try
            {
                ViewBag.UploaderProfile = YoutubeHelper.GetUserInfo(video.Author);
            }
            catch (Exception)
            {
                if (video.Author != video.Uploader)
                {
                    try
                    {
                        ViewBag.UploaderProfile = YoutubeHelper.GetUserInfo(video.Uploader);
                    }
                    catch (Exception)
                    {

                    }
                }

            }

            //ViewBag.BingResults = LiveHelper.GetBingSearchResults(video.Title);
            try
            {
                ViewBag.TwitterResults = TwitterHelper.GetTweets(video.Title);
            }
            catch (Exception)
            {

            }


            //ViewBag.Rating = YoutubeHelper.GetVideoRating(video.Id);
            ViewBag.Title = ViewBag.Title + " - " + video.VideoId;
            return View("VideoPage", video);

        }

        [OutputCache(Duration = 3600, VaryByParam = "id;page")]
        public ActionResult Comments(string id, string page)
        {
            if (string.IsNullOrEmpty(page))
            {
                return new PermanentRedirectResult("~/Home/Comments/" + id + "/0");
            }
            int pageNumber = 0;
            int.TryParse(page, out pageNumber);
            Video video = null;
            try
            {
                video = YoutubeHelper.GetById(id);
            }
            catch (GDataRequestException ex)
            {
                if (ex.ResponseString.Contains("Private") || ex.ResponseString.Contains("not found"))
                {
                    return new PermanentRedirectResult("~/");
                }
            }

            ViewBag.Title = video.Title;
            if (video.CommmentCount > 0)
            {
                Feed<Comment> comments = YoutubeHelper.GetComments(id, pageNumber);
                ViewBag.Comments = comments;
            }
            ViewBag.RelatedVideos = YoutubeHelper.GetRelatedVideos(id);
            try
            {
                ViewBag.UploaderProfile = YoutubeHelper.GetUserInfo(video.Author);
            }
            catch (Exception)
            {
                if (video.Author != video.Uploader)
                {
                    try
                    {
                        ViewBag.UploaderProfile = YoutubeHelper.GetUserInfo(video.Uploader);
                    }
                    catch (Exception)
                    {

                    }
                }

            }

            //ViewBag.BingResults = LiveHelper.GetBingSearchResults(video.Title);
            try
            {
                ViewBag.twitterresults = TwitterHelper.GetTweets(video.Title);
            }
            catch (Exception)
            {

            }


            //ViewBag.Rating = YoutubeHelper.GetVideoRating(video.Id);
            if (pageNumber > 0)
            {
                ViewBag.Title = "Comments Page " + pageNumber.ToString() + " On " + ViewBag.Title;
            }
            else
            {
                ViewBag.Title = "Comments On " + ViewBag.Title;
            }

            return View("_CommentsPage", video);

        }

        [OutputCache(Duration = 7200, VaryByParam = "id")]
        public ActionResult ShowLists(string id)
        {
            Feed<Playlist> lists = null;
            try
            {
                lists = YoutubeHelper.GetPlaylistsByAuthor(id);
                if (lists.TotalResults < 1)
                {
                    ViewBag.Robots = SEOHelper.NoIndex;
                }
                ViewBag.Title = lists.AtomFeed.Title;
            }
            catch (Exception ex)
            {
                if (ex is GDataRequestException)
                {
                    return new PermanentRedirectResult("~/");
                }

            }


            Feed<Video> feed = YoutubeHelper.GetFavorites(id);
            try
            {
                if (feed.Entries != null && feed.Entries.Count() > 0)
                {
                    ViewBag.Favorites = feed;
                }
            }
            catch (Exception ex)
            {
                if (ex is GDataRequestException)
                {
                    GDataRequestException gdataEx = (GDataRequestException)ex;
                    if (!gdataEx.ResponseString.Contains("Access not allowed to favorites of requested user"))
                    {
                        return new PermanentRedirectResult("~/");
                    }
                }
                else
                {
                    return new PermanentRedirectResult("~/");
                }

            }
            try
            {
                ViewBag.UserProfile = YoutubeHelper.GetUserInfo(id);
                ProfileEntry profile = ViewBag.UserProfile as ProfileEntry;
                var thumbnail = (from e in profile.ExtensionElements
                                 where e.XmlName == "thumbnail"
                                 select (XmlExtension)e).SingleOrDefault();
                if (thumbnail != null)
                {
                    var thumbnailUrl = thumbnail.Node.Attributes["url"].Value;
                    ViewBag.UserThumbnail = thumbnailUrl;
                }
            }
            catch (Exception)
            {
                return new PermanentRedirectResult("~/");
            }



            ViewBag.Title = id + "'s Favorites and Playlists";
            Feed<Subscription> subscriptions = YoutubeHelper.GetUserSubscriptions(id);
            try
            {
                if (subscriptions.Entries != null && subscriptions.Entries.Count() > 0)
                {
                    ViewBag.UserSubscriptions = subscriptions;
                }
            }
            catch (Exception ex)
            {

                if (ex is GDataRequestException)
                {
                    GDataRequestException gdataEx = (GDataRequestException)ex;
                    if (!gdataEx.ResponseString.Contains("urrently"))
                    {
                        return new PermanentRedirectResult("~/");
                    }
                }
                else
                {
                    return new PermanentRedirectResult("~/");
                }
            }
            return View("_Lists", lists);
        }

        public ActionResult Favorites()
        {

            if (YoutubeHelper.AccessToken == null)
            {
                return Authenticate();
            }
            Feed<Video> feed = YoutubeHelper.GetFavorites();
            ViewBag.Title = "Your Favorites Favorites";
            ViewBag.Robots = SEOHelper.NoIndex;
            return View("Default", feed);
        }

        [OutputCache(Duration = 3600, VaryByParam = "id")]
        public ActionResult SpecialVideoList(string id)
        {
            Feed<Video> feed = YoutubeHelper.GetVideosFromPlayList(id);
            try
            {
                ViewBag.Title = feed.AtomFeed.Title.Text;
            }
            catch (Exception)
            {
                return new PermanentRedirectResult("~/");
            }

            return View("Default", feed);
        }

        [OutputCache(Duration = 3600, VaryByParam = "id;page")]
        public ActionResult Category(string id, string page)
        {
            if (string.IsNullOrEmpty(page))
            {
                return new PermanentRedirectResult("~/Home/Category/" + id + "/0");
            }
            int pageNumber = 0;
            int.TryParse(page, out pageNumber);
            Feed<Video> feed = YoutubeHelper.GetVideosByTagOrCategory(id, pageNumber);
            List<VideoCategory> categories = ViewBag.Categories;
            var catExists = categories.Where(a => a.Term == id);
            if (catExists.Any())
            {
                string label = catExists.First().Label;
                if (pageNumber > 0)
                {
                    ViewBag.Title = label + " Videos " + " - Page " + pageNumber.ToString();
                }
                else
                {
                    ViewBag.Title = label + " Videos ";
                }


            }
            else
            {
                return new PermanentRedirectResult("~/");
            }

            return View("Default", feed);
        }

        [OutputCache(Duration = 1800, VaryByParam = "id;page")]
        public ActionResult Search(string id, string page)
        {

            if (!GoogleHelper.CheckKeyWordAllowed(id))
            {
                return new PermanentRedirectResult("~/");
            }
            if (string.IsNullOrEmpty(page))
            {
                return new PermanentRedirectResult("~/Home/Search/" + System.Web.HttpUtility.UrlPathEncode(id) + "/0");
            }

            int pageNumber = 0;
            int.TryParse(page, out pageNumber);
            //string searchString = Server.UrlDecode(id);
            string searchString = id;
            Feed<Video> feed = YoutubeHelper.SearchVideos(searchString, pageNumber);
            ViewBag.Title = id + " Video Search Results";
            if (pageNumber > 0)
            {
                ViewBag.Title += " - Page " + pageNumber.ToString();
            }
            return View("Default", feed);
        }

        public ActionResult Authenticate()
        {
            if (YoutubeHelper.AccessToken == null)
            {
                String token = Request.QueryString["token"];
                if (string.IsNullOrEmpty(token))
                {
                    string authSubUrl = AuthSubUtil.getRequestUrl(this.HttpContext.Request.Url.ToString(), "http://gdata.youtube.com", false, true);
                    return Redirect(authSubUrl);
                }
                YoutubeHelper.AccessToken = AuthSubUtil.exchangeForSessionToken(token, null).ToString();
                return Index(null, null);
            }
            else
            {
                return Index(null, null);
            }
        }
    }
}
